package cn.ml.sboot11.controller;

import cn.ml.sboot11.entity.Student;
import cn.ml.sboot11.entity.User;
import cn.ml.sboot11.mapper.UserMapper;
import cn.ml.sboot11.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/list3",produces = "application/json;charset=utf-8")
    @ResponseBody  //返回json数据必须加此注解,不会走视图解析器，直接返回字符串
    public List<User> list3() throws ParseException, InterruptedException {
        studentService.countDown();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<User> users = userMapper.selectList(null);
        return users;
    }

    @GetMapping("/hello")
    @ResponseBody //返回字符串
    public String hello(){
        return "你好。。SpringBoot。。。嘻dafad嘻";
    }

    @GetMapping("/list")
    public ModelAndView list() throws ParseException, InterruptedException {
        studentService.countDown();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<Student> students = studentService.list2(null);
        Map<String,Object> map = new HashMap<>();
        map.put("students",students);
        return new ModelAndView("listStudent",map);
    }

    @GetMapping("/show")
    public String show(ModelMap map,Integer id){
        map.put("student",studentService.selectOne(id));
        return "showStudent";
    }

    @GetMapping("/add")
    public String add(){
        return "addStudent";
    }

    @PostMapping("/add")
    public String add(Student student){
        studentService.save(student);
        return "redirect:show?id="+student.getId();
    }

    @GetMapping("/update")
    public String update(Integer id,ModelMap map){
        map.put("student",studentService.selectOne(id));
        return "updateStudent";
    }

    @PostMapping("/update")
    public String update(Student student){
        studentService.update(student);
        return "redirect:show?id="+student.getId();
    }

    @GetMapping("/delete")
    public String delete(Integer id){
        studentService.delete(id);
        return "redirect:list";
    }

}
